package org.simple.learning.spring.boot.service.adapter;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 项目名称：spring-boot-learning
 * 类名称：FoodAdapters
 * 类描述：FoodAdapters
 * 创建时间：2022/11/9
 *
 * @author jiangjunjie   (E-mail:jiangjunjie@foursmile001.com)
 * @version v1.0
 */
@Component
public class FoodAdapters implements InitializingBean {

    @Autowired
    private ApplicationContext context;

    private final Map<Long, FoodAdapter> adapters = new ConcurrentHashMap<>();

    @Override
    public void afterPropertiesSet() {
        Map<String, FoodAdapter> foodAdapterMap = context.getBeansOfType(FoodAdapter.class);
        foodAdapterMap.values().forEach(
                foodAdapter -> adapters.put(foodAdapter.getTypeId(), foodAdapter)
        );
    }

    public FoodAdapter getService(Long id) {
        FoodAdapter foodAdapter = adapters.get(id);
        if (foodAdapter == null) {
            throw new UnsupportedOperationException();
        } else {
            return foodAdapter;
        }
    }

}
